﻿/*
COPYRIGHT (C) 2011-2012 Raynald Messié

THIS FILE IS PART OF SCRUMPILOT.

SCRUMPILOT IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUMPILOT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUMPILOT. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using ScrumPilot.Domain;
using ScrumPilot.TFSHelpers;

namespace ScrumPilot.Helpers
{
    public static class SPHelpers
    {
        public static void UploadPhotoinDB(HttpPostedFileBase file, Int32 iCurrentUser)
        {
            Int32 length = file.ContentLength;

            var tempImage = new byte[length];
            file.InputStream.Read(tempImage, 0, length);
            byte[] i16 = ResizeImage.ResizeSquare(tempImage, 16);
            byte[] i32 = ResizeImage.ResizeSquare(tempImage, 32);
            byte[] i64 = ResizeImage.ResizeSquare(tempImage, 64);
            byte[] i96 = ResizeImage.ResizeSquare(tempImage, 96);
            using (var unitOfWork = new UnitOfWork())
            {
                var usr = unitOfWork.UserRepositery.GetById(iCurrentUser);
                if (usr.userimage == null)
                {
                    usr.userimage = new userimage
                             {
                                 userid = iCurrentUser,
                                 contenttype = file.ContentType,
                                 img32 = i32,
                                 img16 = i16,
                                 img64 = i64,
                                 img96 = i96
                             };

                }
                else
                {
                    usr.userimage.contenttype = file.ContentType;
                    usr.userimage.img32 = i32;
                    usr.userimage.img16 = i16;
                    usr.userimage.img64 = i64;
                    usr.userimage.img96 = i96;
                }
                unitOfWork.UserRepositery.Update(usr);
                unitOfWork.Save();
            }
        }

        public static user User(int id)
        {
            using (var unitOfWork = new UnitOfWork())
            {
                return unitOfWork.UserRepositery.GetById(id);
            }
        }

        public static Boolean IsAdmin(String id)
        {
            int i;
            if (int.TryParse(id, out i))
                return User(i).isadmin;
            return false;
        }

        public static Boolean IsAdmin(int id)
        {
            return User(id).isadmin;
        }

        public static string FormatTFSServerUrl(String url, String port, String dir)
        {
            String urlRet = String.Format("http://{0}:{1}/", url, port);
            urlRet += !String.IsNullOrEmpty(dir) ? dir + "/" : "";
            return urlRet;
        }

        public static string FormatTFSServerUrl()
        {
            using (var unitOfWork = new UnitOfWork())
            {
                return (unitOfWork.TfsServerParamsRepository.GetOne().FormattedUrl);
            }
        }

        public static Boolean SetSessionValues(HttpContextBase ht, TFSServices tfs = null)
        {
            Boolean bRet = false;
            if (ht.User.Identity.IsAuthenticated)
            {
                if (ht.Session != null && ht.Session["username"] == null)
                    ht.Session["username"] = String.Empty;
                if (String.IsNullOrWhiteSpace(ht.Session["username"].ToString()))
                {
                    using (var unitOfWork = new UnitOfWork())
                    {
                        int id;
                        if (Int32.TryParse(ht.User.Identity.Name, out id))
                        {
                            user usr = unitOfWork.UserRepositery.GetById(id);
                            if (usr != null)
                                ht.Session["username"] = usr.name;

                            bRet = true;
                        }
                        else
                        {
                            // identity problem = disconnect session
                            ht.Session.Clear();
                        }
                    }
                }
                // Set TFS credential in Session
                if (tfs != null && tfs.IsAuthenticated)
                {
                    ht.Session["TFSServer"] = tfs;
                    ht.Session["TFSNetCredential"] = tfs.TFSNetCredential;
                }
            }
            else if (!ht.User.Identity.IsAuthenticated)
                ht.Session["username"] = String.Empty;

            return bRet;
        }

        public static TFSServices CheckTFSServiceInSession(HttpContextBase ht)
        {
            if (ht.Session != null && ht.Session["TFSNetCredential"] != null)
            {
                var ncd = ht.Session["TFSNetCredential"] as NetworkCredential;
                if (ncd != null)
                {
                }
            }
            return null;
        }

        //public static void SetAssignedTo<T>(T wie, int userID) where T : IIWorkItem
        //{
        //    if (userID >= 0)
        //    {
        //        SetAssignedTo(wie, DB.users.First(p => p.userid == userID));
        //    }
        //}

        //public static void SetAssignedTo<T>(T wie, String username) where T : IIWorkItem
        //{
        //    if (!String.IsNullOrWhiteSpace(username))
        //    {
        //        var usr = DB.users.FirstOrDefault(p => p.name == username);
        //        if (usr != null)
        //            SetAssignedTo(wie, usr);
        //    }
        //}

        //public static void SetAssignedTo<T>(T wie, user usr) where T : IIWorkItem
        //{
        //    if (usr != null)
        //    {
        //        wie.AssignedTo = usr.name;
        //        wie.AssignedToID = usr.userid;
        //    }
        //}

    }

    public class NoCache : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
            filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
            filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            filterContext.HttpContext.Response.Cache.SetNoStore();

            base.OnResultExecuting(filterContext);
        }
    }

    public enum ExpertLevelScoring
    {
        Easy = 1, Normal = 3, Hard = 5
    }
    public enum TaskPriorityScoring
    {
        Low = 1, Normal = 3, High = 5
    }
    public enum TaskDurationScroring
    {
        Short = 1, Normal = 3, Long = 5
    }
    public enum UserStoryRank
    {
        Must = 999, Should = 1999, Could = 2999
    }

    #region ImageHelper

    public static class ResizeImage
    {
        public static Byte[] ResizeSquare(Byte[] aImg, int newSize)
        {
            MemoryStream stream = null;
            try
            {
                stream = new MemoryStream(aImg);
                Image img = Image.FromStream(stream);

                int w = img.Width;
                int h = img.Height;
                if (!(h < newSize && w < newSize)) // just a copy
                {
                    double scalefactor = (w > h ? (double)newSize / w : (double)newSize / h);
                    w = (int)(w * scalefactor);
                    h = (int)(h * scalefactor);
                    Image newImg = img.GetThumbnailImage(w, h, null, IntPtr.Zero);
                    stream = new MemoryStream();
                    newImg.Save(stream, img.RawFormat);
                    aImg = stream.ToArray();
                }
                stream.Dispose();
            }
            finally
            {
                if (stream != null) stream.Dispose();
            }

            return (aImg);
        }
    }

    public class ImageResult : ActionResult
    {
        // Thank to Sean for this
        // http://byatool.com/index.php/mvc/asp-net-mvc-upload-image-to-database-and-show-image-dynamically-using-a-view/
        //

        public String ContentType { get; set; }
        public byte[] ImageBytes { get; set; }
        public String SourceFilename { get; set; }

        public ImageResult(String sourceFilename, String contentType)
        {
            SourceFilename = sourceFilename;
            ContentType = contentType;
        }

        public ImageResult(byte[] sourceStream, String contentType)
        {
            ImageBytes = sourceStream;
            ContentType = contentType;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.Clear();
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = ContentType;

            if (ImageBytes != null)
            {
                MemoryStream stream = null;

                try
                {
                    stream = new MemoryStream(ImageBytes);
                    stream.WriteTo(response.OutputStream);
                }
                finally
                {
                    if (stream != null) stream.Dispose();
                }
            }
            else
            {
                response.TransmitFile(SourceFilename);
            }
        }
    }

    #endregion

    /// <summary>
    /// Helper for using LESS server-side
    /// </summary>
    public class LessTransform : IBundleTransform
    {
        public void Process(BundleContext context, BundleResponse response)
        {
            response.Content = dotless.Core.Less.Parse(response.Content);
            response.ContentType = "text/css";
        }
    }
}